package com.mq.producer.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class SendController {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RabbitAdmin rabbitAdmin;

    public void send() {
        // 声明一个队列
        Map<String, Object> param = new HashMap<>();
        // 队列存活时长
        param.put("x-message-ttl", 5000);
        // 消息失效后，转发到的路由
        param.put("x-dead-letter-exchange", "竞拍订单死信队列");
        // 消息失效后，转发到的路由下的队列
        param.put("x-dead-letter-routing-key", "竞拍开始");
        String uuid = UUID.randomUUID().toString();
        String queueName = "竞拍订单-" + uuid;
        Queue queue = new Queue(queueName, false, false, true, param);
        rabbitAdmin.declareQueue(queue);

        // 建立绑定关系
        String exchangeName = "普通队列";
        Binding binding = BindingBuilder.bind(queue).to(new DirectExchange(exchangeName)).with(queueName);
        rabbitAdmin.declareBinding(binding);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", uuid);
        jsonObject.put("msg", "我是一条消息...用于死信队列测试。" + "    " + uuid);

        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, queueName, jsonObject.toJSONString());
        System.out.println("发送完成");
        System.out.println("发送内容##" + jsonObject.toJSONString());
    }
}
